#include "productiondetaildialog.h"
#include "ui_productiondetaildialog.h"
#include <QSqlQuery>
#include <QMessageBox>
#include <QFileDialog>
#include <QDate>
#include <QTextStream>

ProductionDetailDialog::ProductionDetailDialog(int employeeId, const QString &toyName, const QString &processName, 
                                               const QString &startDate, const QString &endDate, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ProductionDetailDialog),
    m_employeeId(employeeId),
    m_toyName(toyName),
    m_processName(processName),
    m_startDate(startDate),
    m_endDate(endDate)
{
    ui->setupUi(this);
    setupUI();
    loadInitialData();
}

ProductionDetailDialog::~ProductionDetailDialog()
{
    delete ui;
}

void ProductionDetailDialog::setupUI()
{
    setWindowTitle("生产详情查询");
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    
    // 设置初始值
    ui->lineEditToyName->setText(m_toyName);
    if (!m_processName.isEmpty() && m_processName != "无工序") {
        ui->lineEditProcessName->setText(m_processName);
    }
    
    // 设置日期
    ui->dateEditStart->setDate(QDate::fromString(m_startDate, "yyyy-MM-dd"));
    ui->dateEditEnd->setDate(QDate::fromString(m_endDate, "yyyy-MM-dd"));
    
    // 连接信号和槽
    connect(ui->pushButtonSearch, &QPushButton::clicked, this, &ProductionDetailDialog::onSearch);
    connect(ui->pushButtonReset, &QPushButton::clicked, this, &ProductionDetailDialog::onReset);
    connect(ui->pushButtonExport, &QPushButton::clicked, this, &ProductionDetailDialog::onExport);
    connect(ui->pushButtonClose, &QPushButton::clicked, this, &ProductionDetailDialog::close);
}

void ProductionDetailDialog::loadInitialData()
{
    onSearch();
}

void ProductionDetailDialog::onSearch()
{
    // 清空表格
    ui->tableWidget->setRowCount(0);
    
    // 获取查询条件
    QString toyName = ui->lineEditToyName->text().trimmed();
    QString processName = ui->lineEditProcessName->text().trimmed();
    QString startDate = ui->dateEditStart->date().toString("yyyy-MM-dd");
    QString endDate = ui->dateEditEnd->date().toString("yyyy-MM-dd");
    
    // 查询支持工序维度的生产详情
    QSqlQuery query;
    if (processName.isEmpty() || processName == "无工序") {
        // 查询旧版本表（无工序信息）
        query.prepare("SELECT p.date, p.quantity, t.piece_rate, (p.quantity * t.piece_rate) AS amount "
                      "FROM production p "
                      "JOIN toys t ON p.toy_id = t.id "
                      "WHERE p.employee_id = ? AND t.name = ? AND p.date BETWEEN ? AND ? "
                      "ORDER BY p.date");
        query.addBindValue(m_employeeId);
        query.addBindValue(toyName);
        query.addBindValue(startDate);
        query.addBindValue(endDate);
    } else {
        // 查询新版本表（包含工序信息）
        query.prepare("SELECT pv2.date, pv2.quantity, pv2.piece_rate, pv2.subtotal AS amount "
                      "FROM production_v2 pv2 "
                      "JOIN toys t ON pv2.toy_id = t.id "
                      "JOIN processes p ON pv2.process_id = p.id "
                      "WHERE pv2.employee_id = ? AND t.name = ? AND p.name = ? AND pv2.date BETWEEN ? AND ? "
                      "ORDER BY pv2.date");
        query.addBindValue(m_employeeId);
        query.addBindValue(toyName);
        query.addBindValue(processName);
        query.addBindValue(startDate);
        query.addBindValue(endDate);
    }
    
    if (!query.exec()) {
        QMessageBox::critical(this, "错误", "查询生产详情失败: " + query.lastError().text());
        return;
    }
    
    // 填充表格
    double totalAmount = 0;
    int totalQuantity = 0;
    
    while (query.next()) {
        int row = ui->tableWidget->rowCount();
        ui->tableWidget->insertRow(row);
        
        QString date = query.value(0).toString();
        int quantity = query.value(1).toInt();
        double price = query.value(2).toDouble();
        double amount = query.value(3).toDouble();
        
        ui->tableWidget->setItem(row, 0, new QTableWidgetItem(date));
        ui->tableWidget->setItem(row, 1, new QTableWidgetItem(QString::number(quantity)));
        ui->tableWidget->setItem(row, 2, new QTableWidgetItem(QString::number(price, 'f', 3)));
        ui->tableWidget->setItem(row, 3, new QTableWidgetItem(QString::number(amount, 'f', 3)));
        
        totalAmount += amount;
        totalQuantity += quantity;
    }
    
    // 添加汇总行
    if (ui->tableWidget->rowCount() > 0) {
        int row = ui->tableWidget->rowCount();
        ui->tableWidget->insertRow(row);
        
        QTableWidgetItem *summaryItem = new QTableWidgetItem("合计");
        summaryItem->setFont(QFont("", -1, QFont::Bold));
        ui->tableWidget->setItem(row, 0, summaryItem);
        ui->tableWidget->setItem(row, 1, new QTableWidgetItem(QString::number(totalQuantity)));
        ui->tableWidget->setItem(row, 2, new QTableWidgetItem("--"));
        QTableWidgetItem *totalItem = new QTableWidgetItem(QString::number(totalAmount, 'f', 3));
        totalItem->setFont(QFont("", -1, QFont::Bold));
        ui->tableWidget->setItem(row, 3, totalItem);
    }
    
    // 更新状态栏
    ui->statusLabel->setText(QString("共找到 %1 条记录，总数量 %2 件，总金额 ￥%3")
                            .arg(ui->tableWidget->rowCount() > 0 ? ui->tableWidget->rowCount() - 1 : 0)
                            .arg(totalQuantity)
                            .arg(QString::number(totalAmount, 'f', 3)));
}

void ProductionDetailDialog::onReset()
{
    // 重置查询条件
    ui->lineEditToyName->setText(m_toyName);
    if (!m_processName.isEmpty() && m_processName != "无工序") {
        ui->lineEditProcessName->setText(m_processName);
    } else {
        ui->lineEditProcessName->clear();
    }
    
    // 重置日期
    ui->dateEditStart->setDate(QDate::fromString(m_startDate, "yyyy-MM-dd"));
    ui->dateEditEnd->setDate(QDate::fromString(m_endDate, "yyyy-MM-dd"));
    
    // 重新查询
    onSearch();
}

void ProductionDetailDialog::onExport()
{
    // 打开文件保存对话框
    QString fileName = QFileDialog::getSaveFileName(this, "导出生产详情", "生产详情.csv", "CSV文件 (*.csv)");
    if (fileName.isEmpty()) {
        return;
    }
    
    // 确保文件名以.csv结尾
    if (!fileName.endsWith(".csv", Qt::CaseInsensitive)) {
        fileName += ".csv";
    }
    
    // 导出数据到CSV文件
    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, "导出失败", "无法创建文件: " + fileName);
        return;
    }
    
    QTextStream out(&file);
    
    // 写入表头
    out << "日期,数量,单价,金额\n";
    
    // 写入数据
    for (int row = 0; row < ui->tableWidget->rowCount() - 1; ++row) { // 不导出合计行
        QStringList rowData;
        for (int col = 0; col < ui->tableWidget->columnCount(); ++col) {
            QTableWidgetItem *item = ui->tableWidget->item(row, col);
            rowData << (item ? item->text() : "");
        }
        out << rowData.join(",") << "\n";
    }
    
    file.close();
    QMessageBox::information(this, "导出完成", "生产详情已成功导出到: " + fileName);
}